<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" :width="600">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema } from "./data"
  import * as apis from "/@/api/iam/post"
  
  const emit = defineEmits(["success", "register"])
  const isUpdate = ref(true)
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  })

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields()
    setModalProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate
    if (unref(isUpdate)) {
      data.record = await apis.getPostById({ id: data.record.id })
      await setFieldsValue({
        ...data.record,
      })
    }
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增岗位" : "编辑岗位"))
  async function handleSubmit() {
    try {
      const values = await validate()
      setModalProps({ confirmLoading: true })
      await apis.saveOrUpdatePost(values, isUpdate.value)
      closeModal()
      emit("success")
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
